import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

import '../configs/color_config.dart';
import 'zz_button.dart';

class ZZWebWidget extends StatefulWidget {
  final String url;
  final WebViewController? controller;

  /// 网页title改变时回调，当自定义WebViewController 此属性无效
  final Function(String title)? titleCallBack;

  /// 是否显示底部 返回 前进 主页 按钮
  final bool isShowBottomAction;

  /// 是否显示顶部加载进度条
  final bool isShowProgress;
  const ZZWebWidget(this.url,
      {super.key,
      this.controller,
      this.titleCallBack,
      this.isShowBottomAction = true,
      this.isShowProgress = true});

  @override
  State<ZZWebWidget> createState() => _ZZWebWidgetState();
}

class _ZZWebWidgetState extends State<ZZWebWidget> {
  late WebViewController _controller;
  double _progress = 0;

  @override
  void initState() {
    super.initState();

    if (widget.controller == null) {
      // #docregion platform_features
      late final PlatformWebViewControllerCreationParams params;
      if (WebViewPlatform.instance is WebKitWebViewPlatform) {
        params = WebKitWebViewControllerCreationParams(
          allowsInlineMediaPlayback: true,
          mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
        );
      } else {
        params = const PlatformWebViewControllerCreationParams();
      }

      final WebViewController controller =
          WebViewController.fromPlatformCreationParams(params);
      // #enddocregion platform_features

      controller
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..setBackgroundColor(const Color.fromARGB(0, 0, 0, 0))
        ..setNavigationDelegate(
          NavigationDelegate(
            onProgress: (int progress) {
              debugPrint('WebView is loading (progress : $progress%)');
              if (mounted) {
                setState(() {
                  _progress = progress / 100;
                });
              }
            },
            onPageStarted: (String url) {
              debugPrint(
                  'Page started loading: $url   ${_controller.getTitle()}');
            },
            onPageFinished: (String url) {
              debugPrint(
                  'Page finished loading: $url   ${_controller.getTitle()}');
              reloadTitle();
            },
            onWebResourceError: (WebResourceError error) {
              debugPrint('''
              Page resource error:
              code: ${error.errorCode}
              description: ${error.description}
              errorType: ${error.errorType}
              isForMainFrame: ${error.isForMainFrame}
          ''');
            },
            onNavigationRequest: (NavigationRequest request) {
              if (request.url.startsWith('https://www.youtube.com/')) {
                debugPrint('blocking navigation to ${request.url}');
                return NavigationDecision.prevent;
              }
              debugPrint('allowing navigation to ${request.url}');
              return NavigationDecision.navigate;
            },
            onUrlChange: (UrlChange change) {
              debugPrint('url change to ${change.url}');
            },
          ),
        )
        ..addJavaScriptChannel(
          'Toaster',
          onMessageReceived: (JavaScriptMessage message) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text(message.message)),
            );
          },
        )
        ..loadRequest(Uri.parse(widget.url));

      // #docregion platform_features
      if (controller.platform is AndroidWebViewController) {
        AndroidWebViewController.enableDebugging(true);
        (controller.platform as AndroidWebViewController)
            .setMediaPlaybackRequiresUserGesture(false);
      }
      _controller = controller;
    } else {
      _controller = widget.controller!;
    }
  }

  @override
  dispose() {
    super.dispose();
  }

  reloadTitle() async {
    var title = await _controller.getTitle();
    if (widget.titleCallBack != null) {
      widget.titleCallBack!(title ?? "");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
            child: Stack(
          children: [
            WebViewWidget(controller: _controller),
            _progress >= 1 || !widget.isShowProgress
                ? Container()
                : LinearProgressIndicator(
                    minHeight: 1,
                    backgroundColor: Colors.white,
                    valueColor:
                        const AlwaysStoppedAnimation(ColorConfig.orange),
                    value: _progress,
                  )
          ],
        )),
        widget.isShowBottomAction
            ? Container(
                color: ColorConfig.black,
                child: SafeArea(
                  top: false,
                  child: SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        ZZButton(
                          padding: const EdgeInsets.only(left: 15),
                          width: 50,
                          image: const Icon(Icons.arrow_back_ios,
                              size: 25, color: Colors.white),
                          onTap: () async {
                            await _controller.canGoBack()
                                ? _controller.goBack()
                                : null;
                          },
                        ),
                        ZZButton(
                          padding: const EdgeInsets.only(left: 15),
                          width: 50,
                          image: const Icon(Icons.arrow_forward_ios,
                              size: 25, color: Colors.white),
                          onTap: () async {
                            await _controller.canGoForward()
                                ? _controller.goForward()
                                : null;
                          },
                        ),
                        ZZButton(
                          padding: const EdgeInsets.only(left: 15),
                          width: 50,
                          image: const Icon(Icons.home,
                              size: 25, color: Colors.white),
                          onTap: () {
                            _controller.loadRequest(Uri.parse(widget.url));
                          },
                        )
                      ],
                    ),
                  ),
                ),
              )
            : Container()
      ],
    );
  }
}
